package com.kaizeli.website.query.base;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.logging.log4j.util.Strings;

@Data
@EqualsAndHashCode(callSuper = false)
public class PageQuery extends BaseRequest {
    @Schema(description = "页码")
    private Long pageNo;
    @Schema(description = "每页数量")
    private Long pageSize;
    @Schema(description = "排序字段")
    private String sortBy;
    @Schema(description = "是否升序")
    private Boolean isAsc;

    private String lastEndKey;

    public static final String CREATE_TIME = "create_time";
    public static final String UPDATE_TIME = "update_time";

    public <T> Page<T> toMpPage(OrderItem... orders) {
        // 1.分页条件
        long current = pageNo == null ? 1L : pageNo;
        long size = pageSize == null ? 10L : pageSize;
        Page<T> p = Page.of(current, size);
        // 2.排序条件
        // 2.1.先看前端有没有传排序字段
        if (Strings.isNotBlank(sortBy)) {
            p.addOrder(OrderItem.asc(sortBy));
            //p.addOrder(new OrderItem(sortBy, isAsc));
            return p;
        }
        // 2.2.再看有没有手动指定排序字段
        if (orders != null) {
            p.addOrder(orders);
        }
        return p;
    }

    public <T> Page<T> toMpPage(String defaultSortBy, boolean isAsc) {
        //return this.toMpPage(new OrderItem(defaultSortBy, isAsc));
        return this.toMpPage(OrderItem.asc(defaultSortBy));
    }

    public <T> Page<T> toMpPageDefaultSortByCreateTimeDesc() {
        return toMpPage(CREATE_TIME, false);
    }

    public <T> Page<T> toMpPageDefaultSortByUpdateTimeDesc() {
        return toMpPage(UPDATE_TIME, false);
    }
}
